<template>
    <div class="content flex-col">
        <div class="tenant-header flex-row">
            <div class="tenant-header-left">
                部门管理
            </div>
            <div class="tenant-header-right">
                <a-button type="primary" @click="handleAddDept">
                    <a-icon type="plus" />
                    添加部门
                </a-button>
            </div>
        </div>
        <div class="tenant-content flex-row">
            <div class="tenant-content-tree">
                <el-tree :data="treeData" @node-click="clickNode"
                         :expand-on-click-node="false">
                    <span class="custom-tree-node" slot-scope="{ node, data }">
                        <span>{{ node.label }}</span>
                        <span>
                            <el-button
                                    type="text"
                                    size="mini"
                                    @click.stop="() => appendNode(data)">
                            添加子部门
                            </el-button>
                                <el-button
                                        type="text"
                                        size="mini"
                                        @click.stop="() => removeNode(data)">
                                删除
                            </el-button>
                        </span>
                    </span>
                </el-tree>
            </div>
            <div class="tenant-content-table tenant-table">
                <el-table  :data="users"
                    height="100%"
                >
                    <el-table-column
                            prop="userName"
                            label="帐号">
                    </el-table-column>
                    <el-table-column
                            prop="userAlia"
                            label="用户名称">
                    </el-table-column>
                    <el-table-column
                            prop="userRole"
                            label="用户角色">
                    </el-table-column>

                    <el-table-column>
                        <template slot="header" slot-scope="scope">
                            <el-input
                                    v-model="searchInput"
                                    size="mini"
                                    style="width: 150px;"
                                    placeholder="输入关键字搜索"/>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>
        <div class="tenant_floor">
            <el-pagination
                @size-change="pageSizeChange"
                @current-change="pageChange"
                :current-page="page.currentPage"
                :page-size="page.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </div>

        <el-dialog :title="dialogTitle"
                   :visible.sync="appendDialogVisible"
                   @close="appendDialogVisible = false"
        >
            <el-form :model="form_dept" :rules="deptRules" ref="appendDeptForm" >
                <el-form-item label="名称：" :label-width="formLabelWidth" prop="deptName">
                    <el-input v-model="form_dept.deptName"></el-input>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="small" @click="appendDialogVisible = false">取 消</el-button>
                <el-button size="small" type="primary" @click="appendFormSubmit('appendDeptForm')">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import {getDeptUserList,getRoleList, addRole, deleteRole, editRole, getAuthorityList, getRoleByID} from '@/api/authority'
    import {getDeptList,addDept,deleteDept,createDeptTree} from '@/api/dept'
    export default {
        name: "dept",
        data() {
            return {
                treeData:[],
                roleNameMap:{},
                userTableData: [],
                appendDialogVisible:false,
                dialogTitle: "添加部门",
                form_dept:{
                    deptName:'',
                    parentID:''
                },
                formLabelWidth: '120px',
                deptRules:{
                    deptName:[{required: true, message: '请输入部门名称', trigger: 'blur'}]
                },
                searchInput:'',
                page: {
                    pageSize: 10,
                    currentPage: 1
                },
            }
        },
        computed:{
            users() {
                let {searchInput, userTableData, page: {currentPage, pageSize}} = this;
                let filterData = userTableData.filter(data => !searchInput || data.userName.toLowerCase().includes(searchInput.toLowerCase()) || data.userAlia.toLowerCase().includes(searchInput.toLowerCase()))
                return filterData.slice((currentPage-1)*pageSize,currentPage*pageSize)
            },
            total() {
                return this.userTableData.length;
            }
        },
        methods: {
            appendNode(data){
                this.appendDialogVisible=true;
                this.dialogTitle="添加下级部门";
                this.form_dept.parentID=data.id
            },
            handleAddDept(){
                this.dialogTitle="添加部门";
                this.appendDialogVisible=true;
                this.form_dept.parentID="0";
            },
            removeNode(data){
                deleteDept({deptId:data.id}).then(res=>{
                    //TODO check delete error when has users or sub depts
                    // this.appendDialogVisible=false;
                    if(res.data.code !=200){
                        this.$message({
                            type: 'error',
                            message: res.data.msg
                        });
                        return;
                    }
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.getDeptList();
                });
            },
            clickNode(d,n,s){
                let deptId=d.id;
                getDeptUserList({deptId:deptId}).then((res) => {
                    if(res.data && res.data.success){
                        this.userTableData = [];
                        // console.log(res.data.data)
                        for (let i = 0; i < res.data.data.length; i++) {
                            let user = res.data.data[i];
                            this.userTableData.push({
                                userId: user.userId,
                                userRole: this.roleNameMap[user.roleId],
                                userName: user.username,
                                userAlia: user.name,
                                userDepts: user.depts
                            })
                        }
                    }
                })


            },
            pageSizeChange(value) {
                this.page.currentPage = 1
                this.page.pageSize = value;
            },
            pageChange(value) {
                this.page.currentPage = value;
            },
            appendFormSubmit(formName){
                this.$refs[formName].validate((valid) => {
                    if(valid){
                        addDept({Name:this.form_dept.deptName,
                            ParentID:this.form_dept.parentID
                        }).then(res=>{
                            this.appendDialogVisible=false;
                            this.$message({
                                type: 'success',
                                message: '添加成功!'
                            });
                            this.getDeptList();
                            this.form_dept={}
                        })
                    }
                })
            },
            getDeptList(){
                getDeptList().then((res)=>{
                    let depArr=res.data.data;
                    let tree=createDeptTree(depArr)

                    this.treeData=tree;
                })

                getRoleList({
                    type: "BACK_ROLE"
                }).then((res) => {
                    if (res.data && res.data.code === 200) {

                        let m={};

                        for (let i = 0; i < res.data.data.length; i++) {
                            m[res.data.data[i].id]=res.data.data[i].roleName;

                            this.roleNameMap=m;
                        }
                        // this.role_options = res.data.data;
                    }
                })
            },

        },
        created() {
            this.getDeptList();
        }
    }
</script>

<style scoped>
.tenant-content-tree{
    height: 100%;
    width: 300px;
    flex: 0 0 300px;
}
.tenant-content-table{
    height: 100%;
    width: 100%;
    flex: 1 1 auto;
}
</style>
